/**
 * 全局变量global对象
 * @param map map 对象
 * @param infowindow 弹出窗口对象
 * @param esmUtil 工具类
 * @param plot 军标类
 * @param changeFeature  更改标绘样式时使用
 * @param accidentFeature  事故点对象
 * @param isAddAccident 是否添加事故点
 * @param roadStartPoint 路径规划起点
 * @param roadEndPoint 路径规划终点
 * */

/**
 * 1.地图坐标转经纬度
 *var lonlat =  = ol.proj.transform(evt(rm(evt.coordinate, 'e, 'EPSG:3857', 'EPSG:4326');
 *  var lon = lonlat[0];
 *  var lat = lonlat[1];
 *2.经纬度转地图坐标
 * var coordinate =  = ol.proj.transform(lon(lonlat, 'EPSG:4326', 'EPSG:3857');
 *  var x = coordinate[0];
 *  var y = coordinate[1];
 */
//行政图和卫星图的图片数据加载list
var xzImageResourceList=[];
var wxImageResourceList=[];
var resourceType=1;
var global={};
var feature,icon,plotType;
var ESM = {};
var queryDataType = "wzcbd,zddw,xfsy,xfs,yjdw,sczz,xfdw";
var eventCoordinate;//经纬度
var initLat;
var initLng;
//百度地图层
var baiduMapLayer,baiduWeiXinMapLayer,cva_wLayer;
var runIndex=0;
var mytime = setInterval(function(){showme()}, 100);
function showme(){
	mapInit();
	runIndex += 1;
	if(runIndex>=1) clearInterval(mytime);
}

function mapInit(){
	 //定义工具类
     global.esmUtil = new ESM.Utils();
     
     // 自定义分辨率和瓦片坐标系
     var resolutions = [];
     var maxZoom = 19;
   
     // 计算百度使用的分辨率
     for (var i = 0; i <= maxZoom; i++) {
         resolutions[i] = Math.pow(2, maxZoom - i);
     }
     var tilegrid = new ol.tilegrid.TileGrid({
         origin: [0, 0],
         resolutions: resolutions    // 设置分辨率
     });
     // 判断加载地图的类型
     if (loadMapType=="b"){
    	//行政图
         baiduMapLayer = new ol.layer.Tile({
        	    source: new ol.source.BaiduMap()
        });
         //卫星图
         baiduWeiXinMapLayer = new ol.layer.Tile({
     	    source: new ol.source.BaiduMap({"mapType":"sat"}),
             projection: 'EPSG:3857'
         })
     }else{
    	//行政图
         baiduMapLayer = new ol.layer.Tile({
        	    source: new ol.source.TianMap()
         });
         
         if(mapModel == 1){
        	// 天地图的lable
             cva_wLayer = new ol.layer.Tile({
            	    source: new ol.source.TianMap({"mapType":"label"})
             });
         }
         //卫星图
         baiduWeiXinMapLayer = new ol.layer.Tile({
     	    source: new ol.source.TianMap({"mapType":"sat"}),
             projection: 'EPSG:3857'
         })
     }
    
//     baiduMapLayer.set('name', 'sys_baselayer');
//     baiduMapLayer.set('id', 'sys_baselayer');
     
     // 比例线
     var scaleLineControl = new ol.control.ScaleLine({className:'ol-scale-line'});
     // 创建地图
     global.map =new ol.Map({
    	 interactions: ol.interaction.defaults().extend([new ESM.Drag()]),
    	 controls: ol.control.defaults({
            attributionOptions: {
              collapsible: false
            },
            zoom: false
          }).extend([
            scaleLineControl
         ]),
         layers: loadMapType=="b" ? [baiduMapLayer,baiduWeiXinMapLayer] 
     			: mapModel == 1 ? [baiduMapLayer,cva_wLayer,baiduWeiXinMapLayer]:[baiduMapLayer,baiduWeiXinMapLayer],
         view: new ol.View({
             // 设置成都为地图中心center: ol.proj.transform([125.106361,46.593634], 'EPSG:4326', 'EPSG:3857'),
        	 // 125.106361,46.593634 	成都
        	 // 84.77,45.59				克拉玛依
             center: ol.proj.transform([84.77,45.59], 'EPSG:4326', 'EPSG:3857'),
             zoom: 8,
             minZoom: 3,
             maxZoom: 19,
         }),
         target: 'map'
     });
     
     baiduMapLayer.setVisible(true); //显示行政
     baiduWeiXinMapLayer.setVisible(false); //关闭卫星
     //右键菜单 
	// 空判断
	if(ESM.ContextMenu != undefined){
        var contextmenu = new ESM.ContextMenu(global.map, {
            default_menus:true,
            items: [
                {
                    text: '设为起点',
                    id:'start',
                    classname: 'starting-point ol-contextmenu-icon',
                    callback: function (obj, map){
                        var coord = global.esmUtil.toLonLat(obj.coordinate);
                        geoCoder(coord,function(data){
                            setRoadPointInfo(data.address,'start');
                            setRoadPoint(data.location,data.region,'start');
                        });
                    }
                },
                {
                    text: '设为终点',
                    id:'end',
                    classname: 'endding-point ol-contextmenu-icon',
                    callback: function (obj, map){
                        var coord = global.esmUtil.toLonLat(obj.coordinate);
                        geoCoder(coord,function(data){
                            setRoadPointInfo(data.address,'end');
                            setRoadPoint(data.location,data.region,'end');
                        });
                    }
                },
                {
                    id: 'around',
                },
                {
                    text: '附近搜索',
                    id: 'around_btn',
                    classname: 'around-point ol-contextmenu-icon',
                    callback: function (obj, map){
                        drawCircleByDistance(obj.coordinate,obj.distance,'nearLayer');
                        var coord = global.esmUtil.toLonLat(obj.coordinate);
                        var keyword = $("#allSearchInput").val();
                        var queryDataType = $("#allSearchTypeId").val();
                        queryByDistance(keyword,coord[0],coord[1],obj.distance,queryDataType,'zb',true);
                    }
                }
            ]});
	}

     //--------------------------
    if(ESM.InfoWindow != undefined){
        global.infowindow = new ESM.InfoWindow({
            map:global.map,
            maxWidth:420,
            zIndex:1000
        });
	}
	
     //测距 面积
    if(ol.control.MeasureTool != undefined){
    	var MeasureTool = new ol.control.MeasureTool({
            sphereradius : 6378137,//sphereradius
         });

         global.map.addControl(MeasureTool);
    }
     //地图点击事件
     global.map.on('click', onClickHandler);
     
     global.map.on('pointermove', function (event) {
	 	if(global.map.hasFeatureAtPixel(event.pixel)){
	 		//如果相交，返回相交的图层，并且触发方法
	 		global.map.forEachFeatureAtPixel(event.pixel, function(feature){
	 			// 为移动到的feature发送自定义的消息
	 			feature.dispatchEvent({type: 'pointermove', event: event});
	 		});
	 	}
     });
     /*
      * 三维-s
      * */
//   缩放级别触发事件
//	 global.map.on('zoomend',function(e){
//		 console.log('zoomend');
//		gotoGeoMapLevel(map.getZoom());
//	 });
     
	 // 移动地图位置触发事件
	 global.map.on('moveend', function(event){
		if(!$("#vrMainDiv").is(":hidden")){
			//gotoGeoMapLevel(global.map.getView().getZoom() + 1);
//				var p = global.changeFeature.getGeometry().getCoordinates();
//				 p = ol.proj.transform(p, 'EPSG:3857', 'EPSG:4326');
			//gotoGeoMapLL(p[0],p[1]);
		}
     });
		/*
	      * 三维-end
	      * */
    global.plot = new olPlot(global.map, {
        zoomToExtent: true,
        isClear: true
    })
    
    global.plot.plotDraw.on('drawEnd', onDrawEnd);
    
    getClusterDataList();
	moveCenter();
	setTimeout(function(){getAllMapImages()}, 2000);
};


function getAllMapImages(){
	var params = {"tenantId":tenantId,"type":resourceType};
    $.ajax({
		type : "get",
		url : "/mapimages?t="+new Date().getTime(),
		data: params,
		dataType:"json",
		headers: {"Content-Type": "application/json;charset=utf-8"},
		success : function(data) {
			if(data.data&&data.data.length>0){
				var addtomap=[];
				if(resourceType==1){
					xzImageResourceList=data.data;
				}else if(resourceType==2){
					wxImageResourceList=data.data;
				}
				for(j = 0,len=data.data.length; j < len; j++) {
					var d = data.data[j];
					if(d.imagePos && d.imagePos!=""){
						addtomap.push({url:d.imagePath,extent:d.imagePos,id:d.oid,imageId:d.oid,rotation:d.rotation});
					}
				}
				addImagesToMap(addtomap);
			}
		},error: function(request) {
			layer.msg("获取地图图片数据失败", {time: 2000});
        }
	})
}

function getClusterDataList(){
	var params = {"tenantId":tenantId};
	$.ajax({
		type : "get",
		url : "/teams/cluster?t="+new Date().getTime(),
		data: params,
		dataType:"json",
		headers: {"Content-Type": "application/json;charset=utf-8"},
		success : function(data) {	
			if(data.data){
				clusterDo(data.data);
			}
		},error: function(request) {
			layer.msg("获取聚合数据失败！", {time: 2000});
        }
	});
}


/**
 * 北斗转GPS
 * @param lat
 * @param lng
 * @returns
 */
function bd2gps(lat,lng){
	var gpsLng = Math.floor(lng)+(lng - Math.floor(lng)) * 100.0 / 60.0;
	var gpslat = Math.floor(lat)+(lat - Math.floor(lat)) * 100.0 / 60.0;
	return {"lat":lat,"lng":lng};
}


/**
 * 道路标注回显功能
 * */
function addFeatureToMapRoad(feature,id){
	feature.setId(id);
	var params = feature.get("params");
	feature.set("name",params.name);
	feature.set("desc",params.desc);
	var layer = layerIsExist('geographicEditLayer',global.map);
	if(!layer){
		layer = createSynMarkLayer('geographicEditLayer');
		global.map.addLayer(layer);
	}
	layer.getSource().addFeature(feature);
}

/** 
 * 地图点击事件
 * */
function onClickHandler(event) {
//	var f = global.map.forEachFeatureAtPixel(
//		event.pixel,
//        function(ft, layer){return ft;}
//    );
//    if (f) {
//    	console.info(f);
//        var style = f.getStyle();
//        console.info( '=======style');
//        console.info(style);
//        var image = style.getImage();
//        console.info( '=======console.info(image);');
//        console.info(image);
//        if(image){
//        	var rotation = image.getRotation();
//            console.info(rotation);
//            image.setRotation(rotation + 5);
//            f.setStyle(style);
//        }
//    }
	if(global.map.hasFeatureAtPixel(event.pixel)){
		//如果相交，返回相交的图层，并且触发方法
		global.map.forEachFeatureAtPixel(event.pixel, function(feature){
			// 为移动到的feature发送自定义的消息
			feature.dispatchEvent({type: 'click', event: event});
		});
	}
	var coord = event.coordinate;//地图点击位置的经纬度数值
	feature = global.map.forEachFeatureAtPixel(event.pixel, function (feature) {
		if(feature.get('features')){
			if(feature.get('features').length>1){
				var coordinate_ = feature.getGeometry().getCoordinates();
				global.map.getView().animate({zoom: global.map.getView().getZoom() + 1},{center: coordinate_},{duration:1000});
				return null;
			}else{
				return feature.get("features")[0];
			}
		}else{
			return feature
		}
	})
//	
//	try{
//		var style = feature.getStyle();
//	    var image = style.getImage();
//		var rotation = image.getRotation();
//	    image.setRotation(rotation + 5);
//	    feature.setStyle(style);
//	}catch(e){}
	
     
	if (feature && feature.get('isPlot') && !global.plot.plotDraw.isDrawing()) {
		global.plot.plotEdit.activate(feature);
		if(!(feature.get("params").type=="imageLocation")){
			changeStyle(feature);
		}
		//如果是 事故标点就不让拖动
		if(feature.get("params").recordType=="accLocationCompany"){
			global.plot.plotEdit.deactivate();
		}
	}
	else {
		global.plot.plotEdit.deactivate();
	}
   
   /**
	 * mark点击功能
	 */
	if(feature&&feature.get('cluster')){
		//openMarkWindow(feature);
	}
	
	if(feature&&feature.get('imageClose')){
		//console.info(feature.get('id'));
		var imageId = feature.get('id');
		removeImageByid(imageId);
		$("#"+imageId+"Radio").show();
		$("#"+imageId+"RadioInput").attr("checked",false);
	}
	
		
}

var markerMap=new Map();

/**
 * 绘制结束回调函数
 * */ 
function onDrawEnd1(event){
	var feature = event.feature;
	var layer = layerIsExist('plotImageLayer',global.map);
		if(!layer){
			layer = createImageExtentLayer('plotImageLayer');
			global.map.addLayer(layer);
		}
	layer.getSource().addFeature(feature);
}
function onDrawEnd (event) {
    var feature = event.feature;
    var params = feature.get("params");
    var fid = params.oid?params.oid:createRandomId();
    feature.setId(params.featureId?params.featureId:createRandomId());
	feature.set("name",params.name);
	var iconType = params.recordType;
	if(params.type=="imageLocation"){
    	var extent = feature.getGeometry().getExtent();
    	var imageUrl = feature.get('params').url;
    	var imageId = feature.get('params').imageId;
    	var imageId = feature.get('params').imageId;
    	var id = addImageToMap(extent,imageUrl,imageId,imageId);
    	var layer = layerIsExist('plotImageLayer',global.map);
 		if(!layer){
 			layer = createImageExtentLayer('plotImageLayer');
 			global.map.addLayer(layer);
 		}
 		
 		// 根据imageId 禁用并改为未选中。
// 		$("input[value='"+imageId+"']").attr("disabled",true);
// 		$("input[value='"+imageId+"']").attr("checked",false);
 		
    	feature.set('plotType',plotType);
//    	feature.on("change",imageExtentChange);
    	feature.setId(id);
    	
    	// 会画完删除边框
    	var style = feature.getStyle();
    	style.setStroke(null);
    	feature.setStyle(style);
    	
    	var closeFeature = new ol.Feature({
    		geometry:new ol.geom.Point(ol.extent.getTopRight(extent))
    	});
    	closeFeature.set('imageClose',true);
    	closeFeature.set('id',id);
    	var closeId = 'close' + id;
    	closeFeature.setId(closeId);
    	layer.getSource().addFeature(feature);
    	layer.getSource().addFeature(closeFeature);
    
    	$("#"+imageId+"Radio").hide();
    }else if(params.type=="dot"){
    	var layer = layerIsExist('dotLineLayer',global.map);
 		if(!layer){
 			layer = createDotLineLayer('dotLineLayer');
 			global.map.addLayer(layer);
 		}
 		layer.getSource().addFeature(feature);
    }else if(params.type=='marker'){
    	if(params.action=="传感器位置"){
        	if(markerMap.get(feature.get('name'))!=null){
        		deleteSensorFeatureNoSyn(markerMap.get(feature.get('name')));
        	}
        	markerMap.set(feature.get('name'),feature.getId());
    	}
    	if(params.action=="事故点"){
//    		feature.setId('shigudian_20190614');
        	if(markerMap.get(feature.get('name'))!=null){
        		deleteAccidentFeatureByid(markerMap.get(feature.get('name')));
        	}
        	markerMap.set(feature.get('name'),feature.getId());
    	}
    	var layerId = params.clusterType+'MarkerClusterLayer';
    	var clayer = layerIsExist(layerId,global.map);
 		if(!clayer){
 			clayer = createMakerClusterLayer(layerId,params.clusterImagePath);
 			global.map.addLayer(clayer);
 		}
 		featureIsExist(feature,clayer,true);
 		feature.set('plotType','Marker');
    }else{
    	var layer = layerIsExist('plotLayer',global.map);
 		if(!layer){
 			layer = createSynMarkLayer('plotLayer');
 			global.map.addLayer(layer);
 		}
 		featureIsExist(feature,layer);
    	feature.set('plotType',plotType);
    }
	if(params.isSyn){
		socketSend(feature);
	}
	if(iconType=="accLocationCompany"){
		//获取坐标点
		accidentCompany.lonlat3857 = feature.getGeometry().getCoordinates();
		accidentCompany.lonlat4326 = ol.proj.transform(accidentCompany.lonlat3857,'EPSG:3857','EPSG:4326');
		
		//var json = global.plot.plotUtils.fromFeature(feature);
		////var json = feature;
		//if($._Accident && $._Accident.setLocationEnd){
		//	$._Accident.setLocationEnd(json);
		//}
	}
	if(feature.get('plotType')=="Marker"){
		openInfoWindowByFeature(feature);
	}
	if(iconType=="accLocation"){
		var json = global.plot.plotUtils.fromFeature(feature);
		//var json = feature;
		if($._Accident && $._Accident.setLocationEnd){
			$._Accident.setLocationEnd(json);
		}
	}
	
	global.changeFeature = feature;
	//自定义事故点不激活 不能挪位置
	if(!feature.get("params").recordType=="accLocationCompany"){
		global.plot.plotEdit.activate(feature);
	}
}

/**
 * 地图展示扩散行为
 * 文件路径以明文形式进行传值  这个需要修改
 * */
function spread(x,y,isSyn,token,num){
	isTimeEnd = false;
	var coord = [x,y];
	var feature = new ol.Feature({
		geometry:new ol.geom.Point(coord)
	});
	var layer = layerIsExist('spreadMarkerLayer',global.map);
	if(!layer){
		layer = createSpreadMarkerLayer('spreadMarkerLayer',baseUrl+'/images/start.png');
		global.map.addLayer(layer);
	}else{
		layer.getSource().clear();
	}
	layer.getSource().addFeature(feature);
	showSpreadInfo(coord[0],coord[1],isSyn,gasResultUrl+token,num);
}

/**
 * 地图展示扩散行为
 * 文件路径以明文形式进行传值  这个需要修改
 * */
var isTimeEnd = false;
function spreadByTime(x,y,token,time){
	isTimeEnd = true;
	var coord = [x,y];
	var feature = new ol.Feature({
		geometry:new ol.geom.Point(coord)
	});
	var layer = layerIsExist('spreadMarkerLayer',global.map);
	if(!layer){
		layer = createSpreadMarkerLayer('spreadMarkerLayer',baseUrl+'/images/start.png');
		global.map.addLayer(layer);
	}else{
		layer.getSource().clear();
	}
	layer.getSource().addFeature(feature);
	showSpreadInfoByTime(coord[0],coord[1],gasResultUrl+token,time);
}

function showSpreadInfoByTime(x,y,path,index){
	var params =  {lon:x,lat:y,path:path,index:index};
	$.ajax({
		type:'GET',
		url: baseUrl+'/spread/analysis.jhtml',
		data: params,
		dataType:'JSON',
		ladeview:false,
		success: function(data){
//			console.log("时间非自动播放"+index);
			if(data){
				var result = $.parseJSON(data);
				var format = new ol.format.GeoJSON();
				var features = format.readFeatures(result);
				var layer = layerIsExist('spreadLayer',global.map);
				if(!layer){
					layer = createSpreadLayer('spreadLayer');
					global.map.addLayer(layer);
				}else{
					layer.getSource().clear();
				}
				layer.getSource().addFeatures(features);
			}
		}
	})
}

function showSpreadInfo(x,y,isSyn,path1,index1){
	if(index1>59){
		return;
	}
	var params =  {lon:x,lat:y,path:path1,index:index1};
	$.ajax({
		type:'GET',
		url: baseUrl+'/spread/analysis.jhtml',
		headers: {"Content-Type": "application/json;charset=utf-8"},
		data: params,
		dataType:'JSON',
		success: function(data){
			if(data){
				var result = $.parseJSON(data);
				var format = new ol.format.GeoJSON();
				var features = format.readFeatures(result);
				var layer = layerIsExist('spreadLayer',global.map);
				if(!layer){
					layer = createSpreadLayer('spreadLayer');
					global.map.addLayer(layer);
				}else{
					layer.getSource().clear();
				}
				layer.getSource().addFeatures(features);
				index1++;
				if(!isTimeEnd){
					var method = 'showSpreadInfo(' + x + ',' + y + ',' + isSyn + ',\'' + path1 + '\',' + index1 + ")";
					spreadTimer = setTimeout(method,1000);
					return false;
				}
			}
		}
	})
}

//清空扩散相关的图层
function clearSpreadLayer(){
	clearLayerByIds(['spreadMarkerLayer','spreadLayer'],global.map);
}

/**
 * 第4个功能点
 * */
function changeStyle(feature){
	if(feature.get('plotType')=="Point"||feature.getGeometry().getType()=='LineString'){
		return;
	}
	global.changeFeature = feature;
	$('#popup-closer').removeClass('fireColseIcon');
	if(feature.get('plotType')=="Marker"){
		openInfoWindowByFeature(feature);
	}else{
		var point = feature.getGeometry().getInteriorPoint().getCoordinates();
		var fc = feature.get('fcolor')?global.esmUtil.rgba2Hex(feature.get('fcolor')):global.esmUtil.rgba2Hex('rgba(67, 110, 238, 0.4)');
		var bc = feature.get('scolor')?feature.get('scolor'):'#5E8EDD';
		var name = feature.get('name')?feature.get('name'):'';
		var content = initColorPickerHtml(fc,bc,name);
		openInfoWindow(point,content);
		$('#fcSelector').ColorPicker({
			color: fc,
			onShow: function (colpkr) {
				$(colpkr).fadeIn(500);
				return false;
			},
			onHide: function (colpkr) {
				$(colpkr).fadeOut(500);
				return false;
			},
			onChange: function (hsb, hex, rgb) {
				$('#fcSelector div').css('backgroundColor', '#' + hex);
				$('#fcText').text('#'+hex);
			},
			onSubmit: function (colpkr){
				$(colpkr).fadeOut(500);
				return false;
			}
		});
		
		$('#bcSelector').ColorPicker({
			color: bc,
			onShow: function (colpkr) {
				$(colpkr).fadeIn(500);
				return false;
			},
			onHide: function (colpkr) {
				$(colpkr).fadeOut(500);
				return false;
			},
			onChange: function (hsb, hex, rgb) {
				$('#bcSelector div').css('backgroundColor', '#' + hex);
				$('#bcText').text('#'+hex);
			},
			onSubmit: function (colpkr){
				$(colpkr).fadeOut(500);
				return false;
			}
		});
	}
}

function markerSensorShow(equNo,type,oid,onum){
	closeInfoWindow();
	if(type!='sensor'){
	  global.changeFeature.once('change',synMarkerChange);
	}
	var value = $('#markerText').val();
	if(value==""){
		layer.msg("名称不能为空", {time: 1000});
		return;
	}
	global.changeFeature.set('name',value);
	global.changeFeature.get('params').name=value;
	var image = global.changeFeature.get('params').imagePath;
	if(type=='sensor'){
		global.changeFeature.setStyle(new ol.style.Style({
			image: new ol.style.Icon({
				crossOrigin:'anonymous',
				src : image,
				anchor : [ 0.5, 0.5 ]
			}),
			text : new ol.style.Text({
				text:value,
				offsetY:80,
				font:'bold 18px sans-serif',
				fill: new ol.style.Fill({}),
				stroke: new ol.style.Stroke({color:'#ECF5FF',width:3})
			})
		}));
		//获取获取到的坐标点赋值给每个设备的输入框
//		console.log(global.changeFeature.getGeometry().getCoordinates());
//		console.log(ol.proj.transform(global.changeFeature.getGeometry().getCoordinates(), 'EPSG:3857', 'EPSG:4326')),
		var lonlat3857 = global.changeFeature.getGeometry().getCoordinates();
 		var lon = ol.proj.transform(lonlat3857, 'EPSG:3857', 'EPSG:4326')[0].toFixed(6);
		var lat = ol.proj.transform(lonlat3857, 'EPSG:3857', 'EPSG:4326')[1].toFixed(6);
//		aa=[];
//		aa[0]=ol.proj.transform(global.changeFeature.getGeometry().getCoordinates(), 'EPSG:3857', 'EPSG:4326')[0].toFixed(6);
//		aa[1]=ol.proj.transform(global.changeFeature.getGeometry().getCoordinates(), 'EPSG:3857', 'EPSG:4326')[1].toFixed(6);
//		console.log(aa)
		saveEquipmentPos(equNo,onum,lon,lat,value);
	}
}

/**
 * 坐标标注名称 
 * */
function markerNmShow(id,type,oid,onum){
	closeInfoWindow();
	if(type!='sensor'){
	  global.changeFeature.once('change',synMarkerChange);
	}
	var value = $('#markerText').val();
	if(value==""){
		layer.msg("名称不能为空", {time: 1000});
		return;
	}
	global.changeFeature.set('name',value);
	global.changeFeature.get('params').name=value;
	var image = global.changeFeature.get('params').imagePath;
	if(type=='esm27'){
//		var esmFlag = true;
//		$("span[name='deviceSerialEsmId']").each(function(j,item){
//		    if(Number(item.innerHTML)==value){
//		    	esmFlag=false;
//		    }
//		});
//		if(esmFlag){
//			layer.msg("名称和现有设备ID号码不符合", {time: 1000});
//			deleteEsm27FeatureNoSyn(oid);
//			return;
//		}else{
			deleteEsm27FeatureNoSyn(value+"esm27");
			global.changeFeature.setStyle(new ol.style.Style({
				image: new ol.style.Icon({
					crossOrigin:'anonymous',
					src : image,
					anchor : [ 0.5, 0.5 ]
				}),
				text : new ol.style.Text({
					text:value,
					offsetY:80,
					font:'bold 18px sans-serif',
					fill: new ol.style.Fill({}),
					stroke: new ol.style.Stroke({color:'#ECF5FF',width:3})
				})
			}));
			global.changeFeature.setId(value+"esm27");
//			console.log(global.changeFeature.getGeometry().getCoordinates());
			//获取ESM27坐标点
			var esm27Date = global_realtimeData.get(value);
			if(esm27Date!=null){
				esm27Date.point = global.changeFeature.getGeometry().getCoordinates();
			}
//			esm27Point.put(value,global.changeFeature.getGeometry().getCoordinates());
//		}
	}else if(type=='sensor'){
		global.changeFeature.setStyle(new ol.style.Style({
			image: new ol.style.Icon({
				crossOrigin:'anonymous',
				src : image,
				anchor : [ 0.5, 0.5 ]
			}),
			text : new ol.style.Text({
				text:value,
				offsetY:80,
				font:'bold 18px sans-serif',
				fill: new ol.style.Fill({}),
				stroke: new ol.style.Stroke({color:'#ECF5FF',width:3})
			})
		}));
		//获取获取到的坐标点赋值给每个设备的输入框
//		console.log(global.changeFeature.getGeometry().getCoordinates());
//		console.log(ol.proj.transform(global.changeFeature.getGeometry().getCoordinates(), 'EPSG:3857', 'EPSG:4326')),
		var lonlat3857 = global.changeFeature.getGeometry().getCoordinates();
 		var lon = ol.proj.transform(lonlat3857, 'EPSG:3857', 'EPSG:4326')[0].toFixed(6);
		var lat = ol.proj.transform(lonlat3857, 'EPSG:3857', 'EPSG:4326')[1].toFixed(6);
//		aa=[];
//		aa[0]=ol.proj.transform(global.changeFeature.getGeometry().getCoordinates(), 'EPSG:3857', 'EPSG:4326')[0].toFixed(6);
//		aa[1]=ol.proj.transform(global.changeFeature.getGeometry().getCoordinates(), 'EPSG:3857', 'EPSG:4326')[1].toFixed(6);
//		console.log(aa)
		saveEquipmentPos(onum,lon,lat);
		//esm27Point.put(value,global.changeFeature.getGeometry().getCoordinates());
	}else{
		global.changeFeature.setStyle(new ol.style.Style({
			image: new ol.style.Icon({
				crossOrigin:'anonymous',
				src : baseFileUrl+image,
				anchor : [ 0.5, 0.5 ]
			}),
			text : new ol.style.Text({
				text:value,
				offsetY:20,
				font:'bold 12px sans-serif',
				fill: new ol.style.Fill({}),
				stroke: new ol.style.Stroke({color:'#ECF5FF',width:3})
			})
		}));
	}
}

function polygonStyleChange(fcId,bcId){
	closeInfoWindow();
	var fillColor = $(fcId).text();
	var borderColor = $(bcId).text();
	var featurename = $("#txtfeaturename").val();
	var fc = global.esmUtil.hex2Rgba(fillColor,'0.7');
	global.changeFeature.set('scolor',borderColor);
	global.changeFeature.set('fcolor',fc);
	global.changeFeature.set('name',featurename);
	global.changeFeature.setStyle(new ol.style.Style({
		stroke: new ol.style.Stroke({
            color: borderColor,
            width: 2
          }),
          fill: new ol.style.Fill({
            color: fc
          })
	}));
	global.changeFeature.once('change',synMarkerChange);
}

/**
 * 消防路线
 * */
function activateXx(type){
	activate(type,{type:'dot',isSyn:false});
}

/**
 * 会商绘标，除Marker类型{点  线  面}
 * 默认同步操作
 * */
function consultationMarkDraw(type,params){
	params.type='poly';
	addPolyEngine(type,params);
}
/**
 * 指定标绘类型，开始绘制
 * @param type 标绘类型
 * @param params 标绘参数
 */ 
function activate (type, params) {
	plotType = type;
//	var dragAndDropInteraction = new ol.interaction.DragAndDrop({
//			rotate:true,
//		  formatConstructors: [
//		    ol.format.GeoJSON,
//		    ol.format.KML
//		  ]
//		});
//	var interactions = ol.interaction.defaults().extend([
//	    new ol.interaction.DragRotateAndZoom(),
//	    dragAndDropInteraction
//	 ]);
	
//	var interaction = new ol.interaction.Transform({
//		hitTolerance:2,
//		scale:true,
//		rotate:true,
//		keepAspectRatio:ol.events.condition.always,
//		translate:true,
//		stretch:true
//	});
//	var interactions = ol.interaction.defaults().extend([
//		interaction
//	 ]);
		
	
	var select = new ol.interaction.Select();

	var translate = new ol.interaction.Translate({
	  features: select.getFeatures()
	});
	var rotate=new ol.interaction.DragRotate({
		condition:function(){
			return true
		}
	});
	var interactions = ol.interaction.defaults().extend([
		select,
		translate,
//		rotate
	 ]);
	// 不存在则创建
	if(!global.plot){
        global.plot = new olPlot(global.map, {
            zoomToExtent: false,
            isClear: true
        })
	}
	//params['interactions']=interactions;
    global.plot.plotEdit.deactivate();
    global.plot.plotDraw.active(type, params);
}

// 重新移动到地图初始位置。
function moveCenter () {
//    global.map.getView().animate({zoom: 8}, {center: ol.proj.transform([124.054602,41.847832], 'EPSG:4326', 'EPSG:3857')});
	global.map.getView().animate({zoom: 12}, {center: ol.proj.transform([teamList[0].lon,teamList[0].lat], 'EPSG:4326', 'EPSG:3857')});
}

function moveToSensorPos(initLon,initLat){
	if(initLon&&initLat){
		global.map.getView().animate({zoom: 16}, {center: ol.proj.transform([initLon,initLat], 'EPSG:4326', 'EPSG:3857')});
	}
}

// 放大地图
function zoom(z){
    if(z == 1){
        global.map.getView().animate({zoom: global.map.getView().getZoom() + 1});
    }else{
        global.map.getView().animate({zoom: global.map.getView().getZoom() - 1});
    }
}

// 添加Maker
//function addMaker(type,name,iconType){
//    addMakerEngine({image:icon,name:name,catecd:type,iconType:iconType});
//}

/*
 * 标绘结束后的弹框
 * 根据feature 弹出弹出框
 * */

function openInfoWindowByFeature(feature){
	var point = feature.getGeometry().getCoordinates();
	var id  = '#markerText';
	var value = feature.get('name')?feature.get('name'):'';
	//type 为20的是需要输入是输入名字和数量，其他为需要输入数量
	var obj = feature.get('params');
	var iconType = obj.recordType;
	var oid = obj.oid;
	var storageQuantity = obj.storageQuantity;
	var content='';
	$('#popup-closer').removeClass('fireColseIcon');
	//消防车 
	if(iconType=="8"){
		//消防车
		//var sprayTime = obj.sprayTime;
//		console.log("point:"+JSON.stringify(point))
		content = $._IconBox.getFeatureContent(obj);
		openInfoWindow(point,content);
		$('.ol-popup').css('border',"none");
		obj._point=point;
		$._IconBox.showFeatureEnd(obj);
		$('.ol-popup').addClass('delete-ol-popup');
		$('#popup-closer').addClass('fireColseIcon');
	}else{
		$('.ol-popup').removeClass("delete-ol-popup");
		$('#popup-closer').removeClass('fireColseIcon');
	//todo  删除
//	if(iconType=='yjwz'){
//		content = '<div class="fireDIv"><div class="ca cf fireMain"><div class="fl olInput"><input id="markerText" type="text" value="'+value+'" class="">'
//		+'数量：<input id="markerTextNum" type="text" class="" value="'+storageQuantity+'"></div><div class="fl"><input type="button" value="确定" '
//		+'onClick="markerNmShow(\''+id+'\',\'1\',\''+oid+'\',\''+storageQuantity+'\')" class="olSure fl" >&nbsp'
//		+'<input type="button" value="删除" onClick="remove()" class="olCancel fl"></div></div></div>';
//	}else 
			//选择坐标点的弹出框不 确定修改坐标点名称，删除 删除点
			if(iconType=="accLocationCompany"){
				//return;
				content = '<div class="fireDIv"><div class="ca cf fireMain"><div class="fl olInput">';
				content += '<input id="accLocationCompanyText" type="text"  placeholder="请输入事故点名称" value="'+value+'" class=""></div><div class="fl">';
					
					//如果是创建房间时候才能 删除和确认，如果已经加入房间不能删除
					if(!$._Accident.isInroom()){
						content +='<input type="button" value="确定" id="accLocationCompanyOK"  class="olSure fl" >&nbsp';
						content += '<input type="button" value="删除"  id="accLocationCompanyDEL" class="olCancel fl"></div></div></div>';
					}
					openInfoWindow(point,content);
					//$('#accLocationCompanyText').val(value==""?'事故位置':value);
					//确定
					$('#accLocationCompanyOK').click(function(){
						
						var txtvalue = $('#accLocationCompanyText').val();
						if(txtvalue==""){
							layer.msg('请输入事故点名称!', {
								time: 1000 
							  });
							  return;
						}
						feature.set('name',txtvalue);
						feature.get('params').name=txtvalue;
						var json = global.plot.plotUtils.fromFeature(feature);
						//var json = feature;
						if($._Accident && $._Accident.setLocationEnd){
							$._Accident.setLocationEnd(json);
						}
						closeInfoWindow();
					});
					//如果是创建房间时候才能删除，如果已经加入房间不能删除
						//删除
						$('#accLocationCompanyDEL').click(function(){
							var json = global.plot.plotUtils.fromFeature(feature);
							deleteAccidentFeatureByid(json.id);
							$._Accident.framemax();
						});
					if(!$._Accident.isInroom()){
						//删除 点击 close
						$('#accLocationCompanyOK').parents('#popup-content').prev().click(function(){
							var json = global.plot.plotUtils.fromFeature(feature);
							deleteAccidentFeatureByid(json.id);
							$._Accident.framemax();
						});
					}else{
						$('#accLocationCompanyText').attr('readonly','readonly');
					}
					return;
			}
			if(iconType=="6"){
				//var fid = feature.getId();
				if(feature.get('params')){
					var accidentObj = feature.get('params');
					var name = accidentObj.name?accidentObj.name:'';
					var desc = accidentObj.desc?accidentObj.desc:'';
					var type = accidentObj.accidentType?accidentObj.accidentType:'';
					content = '<div class="olmatter">'
						+'<div class="ca cf"><span class="fl olName">事故点名称：</span><span class="fl olInput"><input id="accName" type="text" value="'+name+'"></span></div>'
						+'<div class="ca cf"><span class="fl olName">事故描述：</span><span class="fl olInput h40"><textarea name="desc" class="textarea" id="accDesc" type="text" rows="">'+desc+'</textarea></span></div>'
						//+'<div class="ca cf"><span class="fl olName">距地面高度：</span><span class="fl olInput"><input id="accHeight" type="text" value="'+groundHeight+'"></span></div>'
						+'<div class="ca cf"><span class="fl olName">事故类型：</span><span class="fl olInput"><input id="accType" type="text" value="'+type+'"></span><span class="fl"></span></div>'
						+'<div class="olbtn"><span class="fl olName">&nbsp;&nbsp;</span><span class="fl"><input type="button" value="确定" onClick="saveAccident()" class="olSure fl">'
						+'&nbsp<input type="button" value="删除" onClick="deleteAccidentFeatureByid(\''+feature.getId()+'\')" class="olCancel fl"></span></div></div>';
					}else{
					content = '<div class="olmatter">'
						+'<div class="ca cf"><span class="fl olName">事故点名称：</span><span class="fl olInput"><input id="accName" type="text" value=""></span></div>'
						+'<div class="ca cf"><span class="fl olName">事故描述：</span><span class="fl olInput h40"><textarea name="desc" class="textarea" id="accDesc" type="text" value="" rows=""></textarea></span></div>'
						//+'<div class="ca cf"><span class="fl olName">距地面高度：</span><span class="fl olInput"><input id="accHeight" type="text" value=""></span></div>'
						+'<div class="ca cf"><span class="fl olName">事故类型：</span><span class="fl olInput"><input id="accType" type="text" value=""></span><span class="fl"></span></div>'
						+'<div class="olbtn"><span class="fl olName">&nbsp;&nbsp;</span><span class="fl"><input type="button" value="确定" onClick="saveAccident()" class="olSure fl">'
						+'&nbsp<input type="button" value="删除" onClick="deleteAccidentFeatureByid(\''+feature.getId()+'\')" class="olCancel fl"></span></div></div>';
					}
			}else if(iconType=="esm27"){
				content = '<div class="fireDIv"><div class="ca cf fireMain"><div class="fl olInput">'
					+'<input id="markerText" type="text" value="'+value+'" class=""></div><div class="fl">'
					+'<input type="button" value="确定" onClick="markerNmShow(\''+id+'\',\'esm27\',\''+feature.getId()+'\',\'0\')" class="olSure fl" >&nbsp'
					+'<input type="button" value="删除" onClick="deleteEsm27FeatureNoSyn(\''+feature.getId()+'\')" class="olCancel fl"></div></div></div>';
			}else if(iconType=="mobileesm27"){
				content = '<div class="accident" onclick="$(this).hide();">';
				content += '<div class="adName"><i></i>'+value.deviceAddress+'</div>';
				content += '<div class="adBox"><ul>';
				for(var i=0;i<value.realData.length;i++){
					var gas = value.realData[i];
					content += '<li class="flex">';
					content += '<div class="">'+gas.gasName+'：</div>';
					content += '<div class="equal">'+gas.gasValue+'</div>';
					content += '</li>';
				}
	            content += '</ul></div></div>';
			}else if(iconType=="sensor"){
				content = '<div class="fireDIv"><div class="ca cf fireMain"><div class="fl olInput">'
					+'<input id="markerText"  type="text" value="'+obj.name+'" class=""></div><div class="fl">'
					+'<input type="button" value="确定" onClick="markerSensorShow(\''+obj.equNo+'\',\'sensor\',\''+oid+'\',\''+obj.address+'\')" class="olSure fl" >&nbsp'
					+'<input type="button" value="删除" onClick="deletSensorPos(\''+feature.getId()+'\',\''+obj.equNo+'\',\''+obj.address+'\')" class="olCancel fl"></div></div></div>';
			}else{
				var _feature = global.plot.plotEdit.getFeature();
				if(!_feature){global.changeFeature = feature;}
				content = '<div class="fireDIv"><div class="ca cf fireMain"><div class="fl olInput">'
					+'<input id="markerText" type="text" value="'+value+'" class=""></div><div class="fl">'
					+'<input type="button" value="确定" onClick="markerNmShow(\''+id+'\',\'0\',\'0\',\'0\')" class="olSure fl" >&nbsp'
					+'<input type="button" value="删除" onClick="remove()" class="olCancel fl"></div></div></div>';
			}
			openInfoWindow(point,content);
	}
}

/**
 * todo
 * 地图添加Maker,
 * @param params {
 *  oid:图标的唯一标示，用来以后判断重复;
 *  name:默认名称;
 *  clusterType：聚合的类型;
 *  imagePath:地图上显示标签图片的全路径;
 *  isCluster:是否聚合，true是，false否；
 *  clusterImagePath:聚合图标的全路径；
 *  isSyn:是否同步;
 *  iconType:用来区分标会完之后在点击的时候的弹框类型
 *  isSave:是否保存记录，
 *  recordType:保存记录的类型,
 *  action:动作描述内容；
 * }
 * 图标画完结束之后调用的方法的返回值包含：params,gis数据
 * 结束：openInfoWindowByFeature
 * onDrawEnd 
*/
function addMakerEngine(params){
    var params_ = {type:'marker'};
    var obj = global.esmUtil.mergeObjects(params_,params);
    activate('Point',obj);
}

/**
 * 扩散方法
 * 
function spread(){
	var params = {};
	params.imagePath="images/start.png";
	params.isCluster=false;
	params.isSyn=false;
	params.isSpread=true;
	params.clusterType="spread";
	params.name="扩散源";
	addMakerEngine(params);
}
*/
/**
 * todo
 * 地图添加线形和面形的数据,
 * @param params { 
 *  oid:图标的唯一标示，用来以后判断重复;
 *  name:默认名称;
 *  isSyn:是否同步;
 *  iconType:用来区分标会完之后在点击的时候的弹框类型
 *  isSave:是否保存记录，
 *  recordType:保存记录的类型,
 *  action:动作描述内容；
 * }
 * @param callBakcFun(feature)
 * 
 * 图标画完结束之后调用的方法的返回值包含：params,gis数据
 * 结束：openInfoWindowByFeature
 * onDrawEnd 
*/
function addPolyEngine(type,params){
    activate(type,params);
}

function goAccidentRoom(){
	var flag = 0;
	var params=null;
	$.ajax({
		type : "post",
		url : baseUrl+"/webApi/roomExist.jhtml",
		data: JSON.stringify(params),
		dataType:"json",
		headers: {"Content-Type": "application/json;charset=utf-8"},
		async: false,
		success : function(data) {	
			if(data.httpCode=="200"){
				if(data.data){
					currentRoomName = data.data;
					flag = 0;
				}else{
					flag = 1;
				}
			}
		},error: function(request) {
			layer.msg("网络错误");
        }
	})
	return flag;
}

function saveAccident(){
	var name = $("#accName").val();
	var desc = $("#accDesc").val();
	var type = $("#accType").val();
	if(name.length<1){
		layer.msg("请填写事故点名称!", {
   		  time: 1000 
   		});
		return false;
	}
	if(desc.length<1){
		layer.msg("请填写事故描述!", {
   		  time: 1000 
   		});
		return false;
	}
	if(type.length<1){
		layer.msg("请填写事故类型!", {
   		  time: 1000 
   		});
		return false;
	}
//	var json = global.plot.plotUtils.fromFeature(feature);
	var obj = global.changeFeature.get('params');
	var fid = global.changeFeature.getId();
	var layer = layerIsExist('accidentMarkerClusterLayer',global.map);

	var params = global.esmUtil.mergeObjects(obj,params_);
	global.changeFeature.set('params',params);
	var params_ = {"name":name,"desc":desc,"accidentType":type,"roomId":currentRoomId};
	closeInfoWindow();
	zhmnAccidentPoint=global.changeFeature.getGeometry().getCoordinates();
	params_.lon = zhmnAccidentPoint[0];
	params_.lat = zhmnAccidentPoint[1];
	
	var feature = layer.getSource().getSource().getFeatureById(fid);
	feature.set('params',params);
	var json = global.plot.plotUtils.fromFeature(feature);
	params_.content = JSON.stringify(json);
	
	$.ajax({
		type:'POST',
		url: baseUrl+'/webApi/insertAccident.jhtml',
		headers: {"Content-Type": "application/json;charset=utf-8"},
		data: JSON.stringify(params_),
		dataType:'JSON',
		success: function(data){
			if(data){
				var Feature = layer.getSource().getSource().getFeatureById(fid);
				Feature.set('params',params);
				socketSend(Feature);
				var result = data.data;
				$('#accidentIcon').css("display","block");
			}
		}
	});
}

//删除事故点
function deleteAccidentFeature(feature){
	var layer = layerIsExist('accidentLayer',global.map);
	if(layer){
		layer.getSource().removeFeature(feature);
		closeInfoWindow();
	}
}

//删除事故点
function deleteAccidentFeatureByid(featureid){
	var layer = layerIsExist('accidentMarkerClusterLayer',global.map);
	if(layer){
		var feature = layer.getSource().getSource().getFeatureById(featureid);
		if(feature){
			layer.getSource().getSource().removeFeature(feature);
			global.plot.plotEdit.deactivate();
			closeInfoWindow();
			var obj = feature.get('params');
//			if(obj.recordType!="accLocation"){
//				var json = global.plot.plotUtils.fromFeature(feature);
//				deleteSynMarker(JSON.stringify(json),feature.get('plotType'),feature);
//			}
			var json = global.plot.plotUtils.fromFeature(feature);
			deleteSynMarker(JSON.stringify(json),feature.get('plotType'),feature);
			$('#accidentIcon').css("display","none");
		}
	}
	
}

//删除事故点（关闭房间删除事故点但是不增加事故记录得删除方法）
function deleteAccidentFeatureNoSyn(featureid){
	var layer = layerIsExist('accidentMarkerClusterLayer',global.map);
	if(layer){
		var feature = layer.getSource().getSource().getFeatureById(featureid);
		if(feature){
			layer.getSource().getSource().removeFeature(feature);
			global.plot.plotEdit.deactivate();
			closeInfoWindow();
		}
	}
}

function deletSensorPos(featureid,equNo,name){
	if(equNo&&name){
		deleteEquipmentPos(featureid,equNo,name);
	}
}

function deleteSensorFeatureNoSyn(featureid){
	var layer = layerIsExist('esm27qMarkerClusterLayer',global.map);
	if(layer){
		var feature = layer.getSource().getSource().getFeatureById(featureid);
		if(feature){
			layer.getSource().getSource().removeFeature(feature);
			global.plot.plotEdit.deactivate();
			closeInfoWindow();
		}
	}
}
//删除坐标点（删除坐标点）
function deleteEsm27FeatureNoSyn(featureid){
	var layer = layerIsExist('esm27qMarkerClusterLayer',global.map);
	if(layer){
		var feature = layer.getSource().getSource().getFeatureById(featureid);
		if(feature){
			layer.getSource().getSource().removeFeature(feature);
			global.plot.plotEdit.deactivate();
			closeInfoWindow();
		}
	}
}

var imgCount=0;
var mapImgList=[];
//截图
function camera() {
	global.map.once('postcompose', function(event) {
		imgCount++;
		var imgName="map"+imgCount+".png";
		const
		canvas = event.context.canvas;
		if (navigator.msSaveBlob) {
			navigator.msSaveBlob(canvas.msToBlob(), imgName);
		} else {
			canvas.toBlob(function(blob) {
				var formData = new FormData();
				formData.append("file",blob,imgName);
				formData.append("enctype","multipart/form-data");
				$.ajax({
					type: 'POST',
				    url: baseUrl+'/common/uploadImg.jhtml',
				    data: formData,
				    processData: false,
				    contentType: false,
				    success:function(data){
				    	if(data.httpCode==200){
				    		layer.msg("保存成功！");
				    		var mapImg={};
				    		mapImg.src=baseFileUrl+data.data.fid;
				    		mapImg.name=imgName;
				    		mapImgList.push(mapImg);
				    		var imgHtml = getMapImgHtml(mapImg);
							$("#mapImgId ul").append(imgHtml);
							if(currentRoomId){
								saveImg(data.data.fid);
							}
				    	}else{
				    		layer.msg("上传失败！");
				    	}
				    }
				});
				//如果想同时保存在本地就释放此方法
				saveAs(blob, 'map.png');
			});
		}
	});
	global.map.renderSync();
}

/*场景的详情*/
function getMapImgHtml(obj){
	var html='';
	html+='<li>';
	html+='<a href="javascript:void(0)"><img src="'+obj.src+'" alt="" /></a>';
	html+='<div class="imgListTxt">'+obj.name+'</div>';
	html+='</li>';
	return html;
}

/*场景的详情*/
function saveImg(fid){
	var params={"path":fid,"roomId":currentRoomId};
	$.ajax({
		type:'post',
		url: baseUrl+'/webApi/mapCamera/saveMapImg.jhtml',
		data:JSON.stringify(params),
		dataType:'JSON',
		headers: {"Content-Type": "application/json;charset=utf-8"},
		success: function(data){
			
		}
	})
}



/**
 * 地理逆编码
 */
function geoCoder(coord,callback){
	$.ajax({
		type:'GET',
		url: baseUrl+'/webApi/geocoder.jhtml',
		data: {lon:coord[0].toFixed(6),lat:coord[1].toFixed(6)},
		dataType:'JSON',
		success: function(data){
			var result = JSON.parse(data);
			if(result.status==0){
				callback(result);
			}
		}
	})
}

//路径规划端点定位
function setRoadPoint(coord,region,id){
	var lon = Number(coord.lon.toFixed(6));
	var lat = Number(coord.lat.toFixed(6));
	var feature = new ol.Feature({
		geometry: new ol.geom.Point(ol.proj.fromLonLat([lon,lat]))
	});
	feature.setId(id);
	var layer = layerIsExist('roadPointLayer',global.map);
	if(!layer){
		layer = createRoadPointLayer('roadPointLayer');
		global.map.addLayer(layer);
	}
	featureIsExist(feature,layer);
	if(id=="start"){
		global.roadStartPoint = lat+','+lon;
		global.roadStartRegion = region;
	}else if(id=='end'){
		global.roadEndPoint = lat+','+lon;
		global.roadEndRegion = region;
	}
	
	if(global.roadStartPoint&&global.roadEndPoint){
		roadView(global.roadStartPoint,global.roadEndPoint,global.roadStartRegion,global.roadEndRegion,global.roadStartRegion,'driving');
	}
}

function showRoadView(type){
	if(global.roadStartPoint&&global.roadEndPoint){
		roadView(global.roadStartPoint,global.roadEndPoint,global.roadStartRegion,global.roadEndRegion,global.roadStartRegion,type);
	}
}


/**
 * start [lat,lon] 起点经纬
 * end   [lat,lon] 终点经纬度
 * start_region 起点所在城市
 * end_region 终点所在城市
 * region  起点所在城市 
 * type 交通类型  driving,riding,walking
 * */
function roadView(start,end,startRegion,endRegion,region,type){
	var params = {};
	params.start = start;
	params.end = end;
	params.type = type;
	params.or = startRegion;
	params.dr = endRegion;
	params.region = region;
	$.ajax({
		type:'GET',
		url: baseUrl+'/webApi/road.jhtml',
		data: params,
		dataType:'JSON',
		success: function(data){
			if(data){
				var result = $.parseJSON(data);
				var format = new ol.format.GeoJSON();
				var json = result.roads[0].geojson;
				var features = format.readFeatures(json);
				var layer = layerIsExist('roadViewLayer',global.map);
				if(!layer){
					layer = creatRoadLayer('roadViewLayer');
					global.map.addLayer(layer);
				}
				addFeatureToLayer(features,layer);
				setRoadInfo(result.roads[0].distance,result.roads[0].duration);
			}
		}
	})
}

/**
 * 清空路径规划相关图层
 * */
function routeClear(){
	global.roadStartPoint = null;
	global.roadEndPoint = null;
	clearLayerByIds(["roadPointLayer","roadViewLayer"],global.map);
}

/**
 * 聚合接口
 * */
function clusterDo(data){
	var fmap = new HashMap();
	var format = new ol.format.GeoJSON();
	var features = format.readFeatures(data);
	features.forEach(function(feature){
		feature.set('cluster',true)
		var prop = feature.getProperties();
		var catecd = prop.catecd;
		if(fmap.containsKey(catecd)){
			fmap.get(catecd).push(feature);
		}else{
			var fs = [];
			fs.push(feature);
			fmap.put(catecd,fs);
		}
	});
	var keys =  fmap.keys();
	for(var i=0;i<keys.length;i++){
		var layerId = keys[i]+"ClusterLayer";
		var layer = layerIsExist(layerId,global.map);
		if(!layer){
			layer = createClusterLayer(layerId,keys[i]);
			global.map.addLayer(layer);
		}
		addFeatureToLayer(fmap.get(keys[i]),layer,true)
	}
}

/**
 * 周边搜索接口
 * lon 经度
 * lat 纬度
 * distance 半径 单位米
 * dataType 查询的数据类型
 * queryType 查询类型{zb 范围搜索  extent 矩形搜索}
 * 注：矩形搜索的时候不传lon,lat,distance  需要传入extent(minx,miny,maxx,maxy)
 * */
function queryByDistance(keyword,lon,lat,distance,dataType,queryType,isBaiduGd){
	var geometry = lon.toFixed(6) + "," + lat.toFixed(6) + "," + distance;
	$.ajax({
		type:'GET',
		url: baseUrl+'/webApi/spaceSearch.jhtml',
		data: {keyword:keyword,dataType:dataType,queryType:queryType,geometry:geometry,isBaiduGd:isBaiduGd},
		dataType:'JSON',
		success: function(data){
			if(data){
				var result = JSON.parse(data);
				setSearchDesc(result.address,distance);
				var format = new ol.format.GeoJSON();
				//queryResultOnMap(result.data);
				var features = format.readFeatures(result.data);
				initAroundSearchResult(features);
			}
		}
	})
}

function setSearchDesc(address,distance){
	var dist = global.esmUtil.formatLength(distance);
	var desc = address?address:'';
	$("#searchDesc").text(address);
	$("#distance").text(dist);
	$("#showSearchPanel").show();
}

function drawCircleByDistance(point,distance,layerId){
	var layer = layerIsExist(layerId,global.map);
	if(!layer){
		layer = createNoStyleLayer(layerId);
		global.map.addLayer(layer);
	}
	drawCircle(point,distance,layer,global.map,global.esmUtil);
}

/**
 * 动画
 * */
function dragCallBack(end,start,feature){
	var radius = global.esmUtil.calculateRadius(start,end);
	var layer = layerIsExist('nearLayer',global.map);
	if(layer){
		layer.getSource().getFeatureById('circle').getGeometry().setRadius(radius);
	}
	var length = global.esmUtil.calculateLength(end,start,true);
	feature.getStyle().getText().setText(length[1]);
}

/**
 * 动态周边搜索
 * */
function mouseUpCallBack(end,start){
	var length = global.esmUtil.calculateLength(end,start,true);
	var point = global.esmUtil.toLonLat(start);
	var keyword = $("#allSearchInput").val();
	var queryDataType = $("#allSearchTypeId").val();
	queryByDistance(keyword,point[0],point[1],parseInt(length[0],10),queryDataType,'zb');
}

/**
 * 周边搜索结果展示
 * */
function queryResultOnMap(data){
	var format = new ol.format.GeoJSON();
	var features = format.readFeatures(data);
	var layer = layerIsExist('sptialSearchLayer',global.map);
	if(!layer){
		layer = createCustomLayer('sptialSearchLayer');
		global.map.addLayer(layer);
	}
	initAroundSearchResult(features);
	//addFeatureToLayer(features,layer,false);
}

/**
 * 点击周边搜索li
 * */
function aroundFeatureShow(featureId){
	var layer = layerIsExist('sptialSearchLayer',global.map);
	if(layer){
		var feature = layer.getSource().getFeatureById(featureId);
		openAroundMarkWindow(feature);
	}
}

/**
 * 周边搜索Feature弹出
 * */
function openAroundMarkWindow(feature){
	var point = feature.getGeometry().getCoordinates();
	var content = '<div><a>'+feature.getProperties().name+'<a></div>';
	openInfoWindow(point,content);
}
/**
 * 清空周边搜索相关图层
 * */
function searchClear(){
	clearLayerByIds(["sptialSearchLayer","nearLayer"],global.map);
	clearResultWindow();
}

/**
 * 先保存同步标绘
 * */
function socketSend(feature){
//	if(currentRoomName){
		var json = global.plot.plotUtils.fromFeature(feature);
        saveSynMarker(JSON.stringify(json),feature.get('plotType'),feature,socketFeature);
//	}
}

/**
 * 同步标绘信息
 * */
function socketFeature(feature,id){
	//feature.setId(id);
	var params_ = {"dataid":id};
	var obj = feature.get('params');
	var params = global.esmUtil.mergeObjects(obj,params_);
	feature.set('params',params);

	var json = global.plot.plotUtils.fromFeature(feature);
	send(JSON.stringify(json));
}

/**
 * 将同步的标绘标注到地图上
 * 
 * */
function positionSynMark(featureJSON){
	var feature = global.plot.plotUtils.toFeature(featureJSON);
	var params = feature.get("params");
	if(params.type=="marker"){
		if(params.action=="传感器位置"){
	 		if(markerMap.get(feature.get('name'))!=null){
	    		deleteSensorFeatureNoSyn(markerMap.get(feature.get('name')));
	    	}
		}
		var clusterType = params.clusterType;
		var layerId = clusterType+"MarkerClusterLayer";
		var markerLayer = layerIsExist(layerId,global.map);
		if(!markerLayer){
			markerLayer = createMakerClusterLayer(layerId,params.clusterImagePath);
			global.map.addLayer(markerLayer);
		}
		featureIsExist(feature,markerLayer,true);
	}else{
		var layer = layerIsExist('plotLayer',global.map);
		if(!layer){
			layer = createSynMarkLayer('plotLayer');
			global.map.addLayer(layer);
		}
		featureIsExist(feature,layer,false);
	}
	//feature.once('change',synMarkerChange);
	//自定义事故点不激活
	if(!params.recordType=="accLocationCompany"){
		global.plot.plotEdit.activate(feature);
	}
	//global.changeFeature = feature;

	if(typeof feature.get('name') != 'undefined'){
		markerMap.set(feature.get('name'),feature.getId());
	}
}

/**
 * 标注 样式更改后同步接口
 * */
function synMarkerChange(event){
	var feature = event.target;
	socketSend(feature);
}


/**
 * 删除选中标绘
 */
function remove () {
	var feature = global.plot.plotEdit.getFeature()||global.changeFeature;
	
	if(feature&&feature.get('isPlot')&&feature.get('params').lineType=="dot"){
		var layer = layerIsExist('dotLineLayer',global.map);
		if(layer){
			layer.getSource().removeFeature(feature);
		}
		global.plot.plotEdit.deactivate();
		return;
	}
	
	if(feature&&feature.get('isPlot')&&!(feature.get('params').type=="imageLocation")){
		var layerId;
		if(feature.get('plotType')=="Marker"){
			var params = feature.get("params");
			layerId = params.catecd+'MarkerClusterLayer';
		}else{
			layerId = "plotLayer";
		}
		var layer = layerIsExist(layerId,global.map);
		if(layer){
			if(layerId.indexOf("MarkerClusterLayer")>-1){
				layer.getSource().getSource().removeFeature(feature);
			}else{
				layer.getSource().removeFeature(feature);
			}
		}
	}
	global.plot.plotEdit.deactivate();
	$('#popup').hide();
	if(feature.get('params').recordType!="sensor"){
		//deleteSynMarker(feature.getId(),feature.get('plotType'),feature.get('params').catecd);
		var json = global.plot.plotUtils.fromFeature(feature);
		deleteSynMarker(JSON.stringify(json),feature.get('plotType'),feature);
	}
}

/**
 * 删除同步标注时，外包一层方法，用来确认是否需要进行同步操作
 * */
function deleteSend(id,plotType,catecd){
	if(currentRoomName){
		deleteSynMarker(id,plotType,catecd);
	}
}

/**
 * 同步删除方法
 * */
function synMarkerRemove(params){
	var layerId;
	if(params.plotType=="Marker"){
		layerId = params.catecd+'MarkerClusterLayer';
	}else{
		layerId = "plotLayer";
	}
	var layer = layerIsExist(layerId,global.map);
	if(layer){
		if(layerId.indexOf("MarkerClusterLayer")>-1){
			var feature = layer.getSource().getSource().getFeatureById(params.id);
			if(feature){
				layer.getSource().getSource().removeFeature(feature);
			}
		}else{
			var feature = layer.getSource().getFeatureById(params.id);
			if(feature){
				layer.getSource().removeFeature(feature);
			}
		}
	}
	global.plot.plotEdit.deactivate();
}

/**
 * 同步删除方法
 * */
function noSynMarkerRemove(params){
	var layerId;
	if(params.properties.plotType=="Marker"){
		layerId = params.properties.params.catecd+'MarkerClusterLayer';
	}else{
		layerId = "plotLayer";
	}
	var layer = layerIsExist(layerId,global.map);
	if(layer){
		if(layerId.indexOf("MarkerClusterLayer")>-1){
			var feature = layer.getSource().getSource().getFeatureById(params.id);
			if(feature){
				layer.getSource().getSource().removeFeature(feature);
			}
		}else{
			var feature = layer.getSource().getFeatureById(params.id);
			if(feature){
				layer.getSource().removeFeature(feature);
			}
		}
	}
	global.plot.plotEdit.deactivate();
}



/**
 * 清空元素标绘图层
 * */
function clearMarkerClusterLayers(){
	//获取地图上的所有图层
	var layers = global.map.getLayers();
	//遍历图层；根据layerid清空图层
	for(var i=0;i<layers.getLength();i++){
		var layer = layers.item(i);
		if(layer.get('id')&&layer.get('id').indexOf("MarkerClusterLayer")>-1){
			//因为元素标绘图层的id都包含‘MarkerClusterLayer’此字符串，这样可以删除所有的元素图层了
			layer.getSource().clear();
		}
	}
}

/**
 * 点击标注弹出
 * */
function openMarkWindow(feature){
	var point = feature.getGeometry().getCoordinates();
	var id = feature.getId();
	var type = feature.get('catecd');
	global.changeFeature = feature;

	var url="";
	if(type=="zddw"){
		url=baseUrl+"/webApi/qryKeyUnitById.jhtml";
	}else if(type=="xfsy"|| type=="xfsyhui"){
		url=baseUrl+"/webApi/qryFacilitiesById.jhtml";
	}else if(type=="yjdw"){
		url=baseUrl+"/webApi/qryTeamsById.jhtml";
	}else if(type=="sczz"){
		url=baseUrl+"/webApi/qryEquipmentById.jhtml";
	}else if(type=="wzcbd"){
		url=baseUrl+"/webApi/qryReservePointDetail.jhtml";
	}else if(type=="xfdw"){
		url=baseUrl+"/webApi/qryFireBrigadeById.jhtml";
	}else if(type=="xfs"){
		url=baseUrl+"/webApi/qryWaterSourseById.jhtml";
	}
	$.ajax({
		type:'post',
		url: url,
		data: JSON.stringify(id),
		dataType:"json",
		ladeview:false,
		headers: {"Content-Type": "application/json;charset=utf-8"},
		success: function(data){
			if(data.httpCode==200){
				if(data.data){
					var content= '';
					if(type=="zddw"){
						content = getUnitDetailForMarkHtml(data.data);
					}else if(type=="xfsy"|| type=="xfsyhui"){
						content = getXFSSDetailForMark(data.data,feature.get('name'),type);
					}else if(type=="yjdw"){
						content = getYYDWDetailForMark(data.data);
					}else if(type=="sczz"){
						content = getSCZZDetailForMark(data.data,feature.get('name'));
						setTimeout(function(){
							$('#equipmentdocview').find('.dgColse').remove();
						},200)

					}else if(type=="wzcbd"){
						content = getWZCBDDetailForMark(data.data,feature.get('name'));
					}else if(type=="xfdw"){
						content = getXFDWDetailForMark(data.data,feature.get('name'));
					}else if(type=="xfs"){
						content = getXFSYDetailForMark(data.data,feature.get('name'));
					}
					openInfoWindow(point,content);
					//动态添加事件
					if(type=="zddw"){
						addEvent();
					}
				}		
			}else{
				layer.msg(data.msg);
			}
		},error: function(request) {
			layer.msg("网络错误");
        }
	})
	
}

/**
 * 点击聚合点弹出
 * */
function openClusterMarkWindow(feature){
	var point = feature.getGeometry().getCoordinates();
	var content = '<div><a>'+feature.getProperties().name+'<a></div>';
	openInfoWindow(point,content);
}

/**
 * 点击左侧结果列表定位
 * @param type 类型
 * @param id 主键
 * */
function leftRecordLocation(lon,lat,type,name,id,other){
	var layerId = type+'ClusterLayer';
	var layer = layerIsExist(layerId,global.map);
	var coords = [];
	if(layer){
		var feature = layer.getSource().getSource().getFeatureById(id);
		coords = feature.getGeometry().getCoordinates();
		centerAndZoom(coords,17);
	}
	return coords;
}

/**
 * 地图搜索结果点击
 * @param type 类型
 * @param id 主键
 * */
function mapSearchLocation(type,id){
	var layerId = type+'ClusterLayer';
	var layer = layerIsExist(layerId,global.map);
	if(layer){
		var feature = layer.getSource().getSource().getFeatureById(id);
		centerAndZoom(feature.getGeometry().getCoordinates(),17);
	}
}

/**
 * 居中放大定位
 * @param point 经纬度点；格式为[x,y]
 * @param zoom  地图放大级别
 * */
function centerAndZoom(point,zoom){
	global.map.getView().animate({center: point}, {zoom: zoom});
}

/**
 * 弹出功能
 * */
function openInfoWindow(point,content){
	global.infowindow.setContent(content);
	global.infowindow.setPosition(point);
}

/**
 * 关闭弹出
 * */
function closeInfoWindow(){
	global.infowindow.close();
}

//图层显隐控制2次封装
function layerVisible(layerId,isVisible){
	controlLayerVisible(layerId,global.map,isVisible);
}

/**
 * 添加图标到地图上
 * */
function addFeatureToMap(json,params){
	var format = new ol.format.GeoJSON();
	var feature = format.readFeature(data);
	var style = new ol.style.Style({
		image : new ol.style.Icon({
			crossOrigin:'anonymous',
			src : baseFileUrl+ params.image,
			anchor : [ 0.5, 0.5 ]
		}),
		text : new ol.style.Text({
			font : '12px Arial',
			text : params.name,
			offsetX : 5,
			fill : new ol.style.Fill({
				
			})
		})
	});
	feature.setStyle(style);
	var layer = layerIsExist(layerId,global.map);
	if(!layer){
		layer = createNoStyleLayer(layerId);
		global.map.addLayer(layer);
	}
	
	layer.getSource().addFeature(feature);
}

/**
 * 获取地图当前范围
 * */
function getMapExtent(){
	return global.map.getView().calculateExtent(global.map.getSize()).toString();
}

function initColorPickerHtml(fc,bc,name){
	var html = "<div class='filling'>";
	html += "<div class='ca cf fillingColor'>";
	html +="<a class='fl'>填充色：</a><div id=\"fcSelector\" class='fl'><div id=\"fc\" style=\"background-color: "+fc+"\"></div><a id=\"fcText\">"+fc+"</a></div>";
	html += "<a class='fl'>边框色：</a><div id=\"bcSelector\" class='fl'><div id=\"bc\" style=\"background-color: "+bc+"\"></div><a id=\"bcText\">"+bc+"</a></div>";
	html +="</div>";
	html += "<div class='ca cf fillingColor'><a class='fl'>名称：</a><input type='text' id='txtfeaturename' value='"+name+"' /></div>";
	html += "<div class='btnUser'><input type=\"button\" value=\"确定\" onclick=\"polygonStyleChange('#fcText','#bcText')\" class='olSure'>&nbsp;&nbsp;<input type=\"button\" value=\"删除\" onclick=\"remove()\" class='olCancel'></div>";
	html += "</div";
	return html;
}


/**
 * 
 * 坐标点拾取功能
 * @param lon经度
 * @param lat 纬度
 * @param callback回调函数
 * */
function openLocationWindow(lon,lat,callback){
	layx.iframe('openMap','定位窗口','/webApi/location?lon='+lon+'&lat='+lat,{
		skin:'asphalt',
		statusBar:true,
		minMenu:false,
		maxMenu:false,
		resizable:false,
	    buttons:[
	        {
	            label:'确定',
	            callback:function(id, button, event){
	                var contentWindow=layx.getFrameContext(id);
	                var point = contentWindow.getPosition();
	                callback(point);
	                layx.destroy(id);
	            }
	        },
	        {
	            label:'取消',
	            callback:function(id, button, event){
	                layx.destroy(id);
	            }
	        }
	    ]
	});
}

function createEditForm(feature,url,width,height) {
	var span = 5;
	var canvas = document.createElement('canvas');
    canvas.width = width+span*2;
    canvas.height = height+span*2;
    var ctx = canvas.getContext("2d");
    var img = new Image();
    img.src = url;
    img.onload = function(){
    	ctx.drawImage(img, 0,0, img.width, img.height,span,span,width,height);    
    	drawEditPoint(span, span);
        drawEditPoint(span, canvas.height-span);
        drawEditPoint(canvas.width-span, span);
        drawEditPoint(canvas.width-span, canvas.height-span);
    };
    
    feature.on('click', function(){
    	var rotation = 0.0;
		if(feature.get('rotation')){
			rotation=feature.get('rotation');
		}
		var id = feature.get('id');
		feature.set('rotation',rotation+Math.PI/12);
		global.images.get(id).rotation=feature.get('rotation');
    	var style = feature.getStyle();
    	feature.setStyle(style);
	});
	feature.on('pointermove', function(event){
//    	console.log(event)
	});
    function drawEditPoint(x,y){
    	ctx.beginPath();
    	ctx.arc(x,y,span-1,0,2*Math.PI,false);
	    ctx.fillStyle='white';
	    ctx.fill();
	    ctx.strokeStyle='#383838';
	    ctx.stroke();
	    ctx.closePath();
    }
    return canvas;
}


function createViewCanvasForm(feature,url,extent) {
	var resolution = global.map.getView().getResolution();
	var width=(extent[2]-extent[0])/resolution;
	var height=(extent[3]-extent[1])/resolution;
	var span = 5;
	var canvas = document.createElement('canvas');
	canvas.extent = extent;
	var zoom = Math.min(1024/width,800/height);
    canvas.width = width*zoom+span*2;
    canvas.height = height*zoom+span*2;
	var ctx = canvas.getContext("2d");
    var img = new Image();
    img.src = url;
    img.onload = function(){
    	ctx.drawImage(img, 0,0, img.width, img.height,span,span,canvas.width,canvas.height);
    };
	canvas.zoom=function(){
		return zoom;
	}
	canvas.update = function(){
		var resolution = global.map.getView().getResolution();
		var extent = this.extent;
		var width=(extent[2]-extent[0])/resolution;
		var height=(extent[3]-extent[1])/resolution;
		this.width = width+span*2;
    	this.height = height+span*2;
		var ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0,0, img.width, img.height,span,span,width,height);
		return this;
	}
    return canvas;
}


/**
 * 添加图片到地图
 * @param extent 经纬度坐标范围[minx,miny,maxx,maxy]
 * @param image 图片的url路径 ‘images/chengdu.png’
 * */
function addImageToMap(extent,image,id,imageId){
	var group = layerIsExist('imageGroup',global.map);
	if(!group){
		group = createGroupLayer('imageGroup');
		global.map.addLayer(group);
	}
	var layer;
	if(id){
		group.getLayers().forEach(function(lay){
			if(lay.get('id')==id){
				layer = lay;
			}
		});
		if(layer&&extent){
			var source = new ol.source.ImageStatic({
				url:image,
				crossOrigin: '',
				projection: 'EPSG:3857',
	            imageExtent: extent
			});
			layer.setSource(source);
		}else{
			layer = new ol.layer.Image({
				source: new ol.source.ImageStatic({
					url:image,
					crossOrigin: '',
					projection: 'EPSG:3857',
		            imageExtent: extent
				})
			});
			layer.set('id',id);
			group.getLayers().push(layer);
		}
	}else{
		layer = new ol.layer.Image({
			source: new ol.source.ImageStatic({
				url:image,
				crossOrigin: '',
				projection: 'EPSG:3857',
	            imageExtent: extent
			})
		});
		id = createRandomId();
		layer.set('id',id);
		group.getLayers().push(layer);
	}
	layer.rotation = 0;
	var center = ol.extent.getCenter(extent);
	layer.on("precompose", evt => {
		const ratio = ol.has.DEVICE_PIXEL_RATIO
		const pixel = global.map.getPixelFromCoordinate(center)
		const ctx = evt.context
		ctx.save()
		ctx.translate(pixel[0] * ratio, pixel[1] * ratio)
		ctx.rotate(evt.target.rotation * Math.PI / 180)
		ctx.translate(-pixel[0] * ratio, -pixel[1] * ratio)
	});
	layer.on("postcompose", evt => {
		const ctx = evt.context
		ctx.restore()
	});
	document.getElementById("moins").addEventListener("click", function () {
		layer.rotation -= 1;
		/*text.value = rotation*/
		layer.changed();
		if(global.images&&global.images.containsKey(layer.get("id"))){
			global.images.get(layer.get("id")).rotation=layer.rotation;
		}
	}, false);
	document.getElementById("plus").addEventListener("click", function () {
		layer.rotation += 1
		/*text.value = rotation*/
		layer.changed();
		if(global.images&&global.images.containsKey(layer.get("id"))){
			global.images.get(layer.get("id")).rotation=layer.rotation;
		}
	}, false);
	
	var imageInfo = {};
	imageInfo.extent = extent.toString();
	imageInfo.url = image;
	imageInfo.imageId = imageId;
	imageInfo.rotation = layer.rotation;
	if(global.images){
		if(global.images.containsKey(id)){
			global.images.remove(id);
		}
	}else{
		global.images = new HashMap();
	}
	global.images.put(id,imageInfo);
	return id;
}

/**
 * 添加图片到地图
 * @param extent 经纬度坐标范围[minx,miny,maxx,maxy]
 * @param image 图片的url路径 ‘images/chengdu.png’
 * */
/*function addImageToMap(extent,image,id,imageId){
	var group = layerIsExist('imageGroup',global.map);
	if(!group){
		group = createGroupLayer('imageGroup');
		global.map.addLayer(group);
	}
	if(id){
		var layer;
		group.getLayers().forEach(function(lay){
			if(lay.get('id')==id){
				layer = lay;
			}
		});
		if(layer&&extent){
//			var source = new ol.source.ImageStatic({
//				url:image,
//				crossOrigin: '',
//				projection: 'EPSG:3857',
//	            imageExtent: extent
//			})
			var source = new ol.source.Vector();
			var feature = new ol.Feature({
			    geometry: new ol.geom.Point([extent[0]-(extent[0]-extent[2])/2,extent[1]-(extent[1]-extent[3])/2])
			});
			feature.set('id',id);
			var resolution = global.map.getView().getResolution();
			var canvas = createEditForm(feature,image,(extent[2]-extent[0])/resolution,(extent[3]-extent[1])/resolution);
			feature.set('canvas',canvas);
			feature.set('rotation',image.rotation);
			var style = function(feature, resolution) {
				var initZoom = resolution;
				if(feature.get('scale')){
					initZoom=feature.get('scale');
				}else{
					feature.set('scale',initZoom);
				}
				if(!feature.get('rotation')){
					feature.set('rotation',0);
				}
		    	return new ol.style.Style({
				    image: new ol.style.Icon({
				    	img: canvas,
	                    imgSize: [canvas.width, canvas.height],
				        anchor: [0.5, 0.5],
				        anchorXUnits: 'fraction',
				        anchorYUnits: 'fraction',
				        opacity: 1,
				        rotation:feature.get('rotation'),
				        scale:initZoom/resolution,
				    })
				});
			}
			feature.setStyle(style);
			source.addFeature(feature);
			layer.setSource(source);
		}else{
//			var layer = new ol.layer.Image({
//				source: new ol.source.ImageStatic({
//					url:image,
//					crossOrigin: '',
//					projection: 'EPSG:3857',
//		            imageExtent: extent,
//		            rotate:50
//				})
//			});
			var sourceFeatures = new ol.source.Vector();
			var layer = new ol.layer.Vector({source: sourceFeatures});

			var feature = new ol.Feature({
			    geometry: new ol.geom.Point([extent[0]-(extent[0]-extent[2])/2,extent[1]-(extent[1]-extent[3])/2])
			});
			feature.set('id',id);
			var resolution = global.map.getView().getResolution();
			var canvas = createEditForm(feature,image,(extent[2]-extent[0])/resolution,(extent[3]-extent[1])/resolution);
			feature.set('canvas',canvas);
			feature.set('rotation',image.rotation);
			var style = function(feature, resolution) {
				var initZoom = resolution;
				var canvas = feature.get('canvas');
				if(feature.get('scale')){
					initZoom=feature.get('scale');
				}else{
					feature.set('scale',initZoom);
				}
				if(!feature.get('rotation')){
					feature.set('rotation',0);
				}
		    	return new ol.style.Style({
				    image: new ol.style.Icon({
				    	img: canvas,
	                    imgSize: [canvas.width, canvas.height],
				        anchor: [0.5, 0.5],
				        anchorXUnits: 'fraction',
				        anchorYUnits: 'fraction',
				        opacity: 1,
				        rotation:feature.get('rotation'),
				        scale:initZoom/resolution,
				    })
				});
			}
			feature.setStyle(style);
			sourceFeatures.addFeature(feature);
			layer.set('id',id);
			group.getLayers().push(layer);
		}
	}else{
		var layer = new ol.layer.Image({
			source: new ol.source.ImageStatic({
				url:image,
				crossOrigin: '',
				projection: 'EPSG:3857',
	            imageExtent: extent
			})
		});
		id = createRandomId();
		layer.set('id',id);
		group.getLayers().push(layer);
	}
	var imageInfo = {};
	imageInfo.extent = extent.toString();
	imageInfo.url = image;
	imageInfo.imageId = imageId;
	if(global.images){
		if(global.images.containsKey(id)){
			global.images.remove(id);
		}
	}else{
		global.images = new HashMap();
	}
	global.images.put(id,imageInfo);
	return id;
}*/

/**
 * 删除场景搭建
 * */
function removeImageByid(id){
	var layer;
	var group = layerIsExist('imageGroup',global.map);
	group.getLayers().forEach(function(lay){
		if(lay.get('id')==id){
			layer = lay;
		}
	});
	if(layer){
		group.getLayers().remove(layer);
	}
	
	var plotLayer = layerIsExist('plotImageLayer',global.map);
	if(plotLayer){
		var feature = plotLayer.getSource().getFeatureById(id);
		plotLayer.getSource().removeFeature(feature);
		
		var closeFeature = plotLayer.getSource().getFeatureById('close'+id);
		plotLayer.getSource().removeFeature(closeFeature);
	}
	
	if(global.images&&global.images.containsKey(id)){
		global.images.remove(id);
	}
}

/**
 * 删除场景搭建历史
 * */
function removeImagesByid(id){
	var layers = [];
	var group = layerIsExist('imagesGroup',global.map);
	if(!group)return;
	group.getLayers().forEach(function(lay){
//		console.log(lay.get('id'));
		if(lay.get('id')==id){
			layers.push(lay);
		}
	});
	
	if(layers&&layers.length>0){
		for(var j = 0,len = layers.length; j < len; j++){
			group.getLayers().remove(layers[j]);
		}
	}
	
//	var plotLayer = layerIsExist('plotImageLayer',global.map);
//	if(plotLayer){
//		var feature = plotLayer.getSource().getFeatureById(id);
//		if(feature!=null){
//			plotLayer.getSource().removeFeature(feature);
//		}
//	}
}


/**
 * 显示场景搭建历史
 * */
function addImagesToMap(images){
	var group = layerIsExist('imagesGroup',global.map);
	if(!group){
		group = createGroupLayer('imagesGroup');
		global.map.addLayer(group);
	}
	var laysers = [];
	for(var i=0;i<images.length;i++){
		var image = images[i];
		var imgExtent = image.extent.split(",");
		var layer = new ol.layer.Image({
			source: new ol.source.ImageStatic({
				url:image.url,
				crossOrigin: '',
				projection: 'EPSG:3857',
	            imageExtent: imgExtent
			})
		});
		var center = ol.extent.getCenter(imgExtent.map(Number));
		layer.rotation = image.rotation;
		
		layer.on("precompose", evt => {
			const ratio = ol.has.DEVICE_PIXEL_RATIO
			const pixel = global.map.getPixelFromCoordinate(center)
			const ctx = evt.context
			const rotation = evt.target.rotation;
			ctx.save()
			ctx.translate(pixel[0] * ratio, pixel[1] * ratio)
			ctx.rotate(rotation * Math.PI / 180)
			ctx.translate(-pixel[0] * ratio, -pixel[1] * ratio)
		});
		
		layer.on("postcompose", evt =>{
			const ctx = evt.context
			ctx.restore()
		});
		/*layer.un("precompose", evt =>{
			
		});
		layer.un("postcompose", evt =>{
			
		});*/
		if(image.id){
			layer.set('id',image.id);
			removeImagesByid(image.id);
		}
		laysers.push(layer);
		group.getLayers().push(layer);
	}
}


/**
 * 显示场景搭建历史
 * */
/*function addImagesToMap(images){
	var group = layerIsExist('imagesGroup',global.map);
	if(!group){
		group = createGroupLayer('imagesGroup');
		global.map.addLayer(group);
	}
	for(var i=0;i<images.length;i++){
		var image = images[i];
//		var layer = new ol.layer.Image({
//			source: new ol.source.ImageStatic({
//				// 全路径才能给同房间推送过去。
//				url:image.url,
//				crossOrigin: '',
//				projection: 'EPSG:3857',
//	            imageExtent: image.extent.split(",")
//			})
//		});
//		if(image.id){
////			console.log(image.id);
//			layer.set('id',image.id);
//			removeImagesByid(image.id);
//		}
//		layer.setZIndex(2);
//		group.getLayers().push(layer);
		
		
		var sourceFeatures = new ol.source.Vector();
		var layer = new ol.layer.Vector({source: sourceFeatures});
		var extent = image.extent.split(",");
		var feature = new ol.Feature({
		    geometry: new ol.geom.Point([extent[0]-(extent[0]-extent[2])/2,extent[1]-(extent[1]-extent[3])/2])
		});
		feature.set('id',image.id);
		var resolution = global.map.getView().getResolution();
		var canvas = createViewCanvasForm(feature,image.url,extent);
		feature.set('canvas',canvas);
		feature.set('rotation',image.rotation);
		var style = function(feature, resolution) {
			var initZoom = resolution;
			var canvas = feature.get('canvas');
			if(feature.get('scale')){
				initZoom=feature.get('scale');
			}else{
				feature.set('scale',resolution);
			}
			console.log((initZoom/resolution)/canvas.zoom())
	    	return new ol.style.Style({
			    image: new ol.style.Icon({
			    	img: canvas,
                    imgSize: [canvas.width, canvas.height],
			        anchor: [0.5, 0.5],
			        anchorXUnits: 'fraction',
			        anchorYUnits: 'fraction',
			        opacity: 1,
			        rotation:feature.get('rotation'),
					scale:(initZoom/resolution)/canvas.zoom()
			        //scale:initZoom/resolution
			    })
			});
		}
		feature.setStyle(style);
		sourceFeatures.addFeature(feature);
		
		if(image.id){
			layer.set('id',image.id);
			removeImagesByid(image.id);
		}
			
		layer.setZIndex(2);
		group.getLayers().push(layer);
	}
}*/

function clearImagesGroup(){
	var group = layerIsExist('imagesGroup',global.map);
	if(group){
		global.map.removeLayer(group);
	}
}

function locationImageActivate(url,imageId){
	var params = {type:"imageLocation",url:url,noSocketSend:true,imageId:imageId};
	activate("RectAngle",params);
}

function imageExtentChange(event){
	var extent = event.target.getGeometry().getExtent();
	var image = event.target.get('params').url;
	var id = event.target.getId();
	var imageId = event.target.get('params').imageId;
	addImageToMap(extent,image,id,imageId);
	
	var plotLayer = layerIsExist('plotImageLayer',global.map);
	if(plotLayer){
		var closeId = 'close' + id;
		var feature = plotLayer.getSource().getFeatureById(closeId);
		if(feature){
			feature.setGeometry(new ol.geom.Point(ol.extent.getTopRight(extent)));
		}
		
	}
}

/**
 * 删除获取图片四角坐标，并清空地图
 * */
function getImageExtent(){
	var result = [];
	var layer = layerIsExist('plotImageLayer',global.map);
	var imageLayer = layerIsExist('imageGroup',global.map);
	if(imageLayer){
		if(global.images){
			result = global.images.values();
		}
	}
	global.images = null;
	clearImageLayer();
	return result;
}

/**
 * 清空场景搭建图层
 * */
function clearImageLayer(){
	var layer = layerIsExist('plotImageLayer',global.map);
	var imageLayer = layerIsExist('imageGroup',global.map);
	if(imageLayer){
		global.map.removeLayer(imageLayer);
		layer.getSource().clear();
		global.plot.plotEdit.deactivate();
		
	}
}

/**
 * 初始化救援记录地图
 * */
function initHistoryMap(){
	if(global.historyMap){
		global.historyMap.clearAll();
	}else{
		global.historyMap = new ESM.HistoryMap({
			element:'historyMap',
			url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}',
			center:[104.094752,30.667451],
			zoom: 8
		});
	}
}

/**
 * 历史记录展示
 * @param featureJSON json字符串
 * */
function showHistoryFeature(featureJSONs){
	var features = [];
	for(var i=0;i<featureJSONs.length;i++){
		var featureJSON = featureJSONs[i];
		if(featureJSON.content&&featureJSON.content!="{}"){
			var feature = global.esmUtil.json2Feature(featureJSON.content);
			features.push(feature);
		}
	}
	
	if(global.historyMap&&features.length>0){
		global.historyMap.addFeatures(features);
	}
}

/**
 * 历史记录清除
 * */
function clearHistoryLayer(){
	if(global.historyMap){
		global.historyMap.clearAll();
	}
}

/**
 * 应急路线
 * @param type 应急路线类型
 * @param color 路线颜色
 * */
function addSpecialLineEvent(type,params){
	params.type=type;
	params.isSpecial=true;
	//var params = {type:type,scolor:color,isSpecial:true};
	activate("Polyline",params);
}

/**
 * 爆炸接口显示
 * @param id 主键
 * @param point[x,y]
 * @param items[{distance:1000,color:'#FF0000'},..]
 * @param image 中心点的图片
 * @param isFill 0填充无边，1无填充有边，2有边有填充
 * @param showDistance 是否显示半径距离
 * */
function addBzy(id,point,items,image,isFill,showDistance,rotation){
	if(rotation>64){
		rotation=64;
	}
	if(point.length<1){
		return false;
	}
	var layerId = id + 'bzyLayer';
	var layer = layerIsExist(layerId,global.map);
	if(layer){
		layer.getSource().clear();
	}else{
		layer = createNoStyleLayer(layerId);
		global.map.addLayer(layer);
	}
	items.sort(global.esmUtil.compare('distance'));
	var marker = new ol.Feature({
		geometry: new ol.geom.Point(point)
	});
	var style = new ol.style.Style({
		image: new ol.style.Icon({
			crossOrigin:'anonymous',
			src: image,
			offset:[0.5,0.5]
		})
	})
	marker.setStyle(style);
	marker.setId(id);
	var inCoords;
	for(var i=0;i<items.length;i++){
		var item = items[i];
		var feature = drawCircleByDis(point,item.distance,item.color,inCoords,isFill,global.esmUtil);
		if(isFill){
			inCoords = feature.getGeometry().getLinearRing(0);
		}
		if(showDistance){
			var coords = feature.getGeometry().getCoordinates();
			var textMarker = new ol.Feature({
				geometry: new ol.geom.Point(coords[0][rotation])
			});
			var content = item.distance + ' 米';
			if(item.distanceUnity){
				content = item.distanceUnity;
			}
			var text_style = new ol.style.Style({
				text: new ol.style.Text({
		        	text: content,
					offsetY: 0,
					fill: new ol.style.Fill({
					      color: '#fff'
					    }),
					backgroundFill: new ol.style.Fill({
						color:'rgba(0, 0, 0, 0.6)'
					}),
					backgroundStroke: new ol.style.Stroke({
						color:item.color,
						width:1
					}),
					padding:[0,5,0,5]
		        })
			});
			textMarker.setStyle(text_style);
			layer.getSource().addFeature(textMarker);
		}
		layer.getSource().addFeature(feature);
	}
	layer.getSource().addFeature(marker);
	layer.setZIndex(3);
}

/**
 * 根据ID清空爆炸源 
 * @param id 主键
 * */
function clearBzy(id){
	var layerId = id + 'bzyLayer';
	var layer = layerIsExist(layerId,global.map);
	if(layer){
		global.map.removeLayer(layer);
	}
}

/**
 * 根据ID清空轻质气体扩散
 * @param id 主键
 * */
function clearBuildGeometryLayer(layerId){
	var layer = layerIsExist(layerId,global.map);
	if(layer){
		global.map.removeLayer(layer);
	}
}


/**
* 根据ID模糊匹配删除一个或者多个图层
**/
function removeLayersByFilter(id_patten){
	global.map.getLayers().forEach(function(layer) {
		if (layer && layer.get('id')){
			if(layer.get('id').indexOf(id_patten)) {
				global.map.removeLayer(layer);
			}
		}
	});
}

/**
 * 打开多个传出窗口
 * @param point 打开位置
 * @param content 弹出内容
 * */
function openMultiPopup(id,point,content){
	var overlay = new ESM.Overlay({
		id:id,
		map:global.map,
		point:point,
		content:content
	});
}

/**
 * 根据点半径生成圆
 * */
function buildGeometryByDis(coord,distance){
	var feature = drawCircleByDis(coord,distance,'#4781d9',null,false,global.esmUtil);
	var layer = layerIsExist("buildGeometryLayer",global.map);
	if(!layer){
		layer = createNoStyleLayer("buildGeometryLayer");
		global.map.addLayer(layer);
	}
	layer.getSource().addFeature(feature);
}

/**
 * 根据多点生成图形
 * @params coords点集合,isBorder需要边框,borderColor边框颜色,fillColor填充颜色,transparency填充透明度（不需要填充0）
 * */
function buildGeometryByCoords(coords,isBorder,borderColor,fillColor,fillTransparency){
	if(coords.length<1){
		return false;
	}
	var point = coords[0];
	coords.push(point);
	var polygon = new ol.geom.Polygon([coords]);
	var strokeObj = null;
	if(isBorder){
		strokeObj = new ol.style.Stroke({
//      color: '#4781d9',
			color: '#'+borderColor,
			width: 2
		});
	}
	var feature = new ol.Feature({
		geometry: polygon
	});
//	var style = new ol.style.Style({
//        stroke:new ol.style.Stroke({
//        	color: '#4781d9',
//			width: 2
//		}),
//        fill: new ol.style.Fill({
//            color: 'rgba(67, 110, 238, 0.4)' 
//        })
//	});
	var style = new ol.style.Style({
		stroke: strokeObj,
		fill: new ol.style.Fill({
//            color: 'rgba(67, 110, 238, 0.4)' 
			color: global.esmUtil.hex2Rgba(fillColor,fillTransparency)
		})
	});
	feature.setStyle(style);
	var layer = layerIsExist("buildGeometryLayer",global.map);
	if(!layer){
		layer = createNoStyleLayer("buildGeometryLayer");
		global.map.addLayer(layer);
	}
	layer.getSource().addFeature(feature);
}

/**
 * 清空绘制图层
 * */
function clearBuildGeometryLayer(){
	clearLayerByIds(['buildGeometryLayer'],global.map);
}

/**
 * 根据经纬生成点
 * */
function addPointByXy(point,id,imagePath){
	deleteAccidentFeatureByid(id);
	var feature = new ol.Feature({
		geometry:new ol.geom.Point(point)
	});
	
	var style = new ol.style.Style({
		image:new ol.style.Icon({
			crossOrigin:'anonymous',
			src : baseFileUrl+imagePath,
			anchor : [ 0.5, 0.5 ]
		}),
		text : new ol.style.Text({
			text:"反定位事故点",
			offsetY:20,
			font:'bold 12px sans-serif',
			fill: new ol.style.Fill({}),
			stroke: new ol.style.Stroke({color:'#ECF5FF',width:3})
		})
	});
	
	feature.setId(id);
	feature.setStyle(style);
	var params = {"name":"反定位事故点"};
	feature.set('params',params);
//	debugger;
//	var objparams = feature.get('params');
//	var params_ = {"name":"反定位事故点"};
//	var params = global.esmUtil.mergeObjects(objparams,params_);
//	global.changeFeature.set('params',params);
	var layer = layerIsExist("pointByXyLayer",global.map);
	if(!layer){
		layer = createNoStyleLayer("pointByXyLayer");
		global.map.addLayer(layer);
	}
	layer.getSource().addFeature(feature);
}

function clearPointByXyLayer(){
	clearLayerByIds(['pointByXyLayer'],global.map);
}

//layerIsExist("imagesGroup",global.map).getSource().getFeatureById(6);
//

function removeFeatureById(id){
	var layer = layerIsExist("pointByXyLayer",global.map);
	if(layer){
		var feature = layer.getSource().getFeatureById(id);
		if(feature){
			layer.getSource().removeFeature(feature);
		}
	}
}

/**
 * 根据layerid和featureid获取feature
 * */
function getFeatureByLayer(layerId,featureId){
	var layer = layerIsExist(layerId,global.map);
	if(layer){
		var feature = layer.getSource().getFeatureById(featureId);
		if(feature){
			return feature;
		}
	}
	return null;
}

/**
 * 更换图标方向
 * */
function changeCarDirection(rate){
	global.changeFeature.get('params').rotation = rate;
	global.changeFeature.changed();
	//转角 transform:rotate(7deg);
	$("#carImgIcon").css('transform','rotate('+rate+'deg)');
	$("#carImgIcon").css('-ms-transform','rotate('+rate+'deg)');
	$("#carImgIcon").css('-moz-transform','rotate('+rate+'deg)');
	$("#carImgIcon").css('-webkit-transform','rotate('+rate+'deg)');
	$("#carImgIcon").css('-o-transform','rotate('+rate+'deg)');
	socketSend(global.changeFeature);
}

/**
 * 刷新位置接口
 * */
function refreshPosition(feature,coord){
	var point = new ol.geom.Point(coord);
	feature.setGeometry(point);
}

//生成随机数
function createRandomId() {
    return (Math.random()*10000000).toString(16).substr(0,4)+'-'+(new Date()).getTime()+'-'+Math.random().toString().substr(2,5);
}
//相机跳转,参数是经纬度
function gotoPointViewBYLon(x,y,zoomNum){
	var coordinate = ol.proj.transform([x,y], 'EPSG:4326', 'EPSG:3857');
	global.map.getView().animate({center:coordinate}, {zoom: zoomNum});
}
//相机跳转,墨卡托
function gotoPointView(x,y,zoomNum){
	if(zoomNum==0){
		zoomNum = global.map.getZoom();
	}
	global.map.getView().animate({center: [x,y]}, {zoom: zoomNum});
}
$(document).keydown(function(event){
    if(event.keyCode == 46){
    	remove()
    }  
});

//清楚画圈 todo
function clean(){
	var lay = null;
	map.getLayers().forEach(function(layer) {
//	  console.log(map);
	  alert(layer.get('id'));
	});
}

/**
* 显示矢量地图
**/
function showDiTu(){
	resourceType=1;
	$('#scenebuildingList').find('li').each(function() {
        removeImagesByid($(this).attr("id"));
    });
	for(j = 0,len=wxImageResourceList.length; j < len; j++) {
		var oid=wxImageResourceList[j].oid;
		removeImagesByid(oid);
	}
//	var layer = getLayerById('sys_baselayer');
//	if(layer) global.map.removeLayer(layer);
//	baiduMapLayer = new ol.layer.Tile({
//		source: new ol.source.BaiduMap()
//     });
//     baiduMapLayer.set('name', 'sys_baselayer');
//     baiduMapLayer.set('id', 'sys_baselayer');
//     baiduMapLayer.setZIndex(0);
//     global.map.addLayer(baiduMapLayer);
	 baiduMapLayer.setVisible(true); //显示行政
     baiduWeiXinMapLayer.setVisible(false); //关闭卫星
     getAllMapImages();
}

/**
* 显示天地图卫星
**/
function showWeiXingTu(){
	resourceType=2;
	$('#scenebuildingList').find('li').each(function() {
        removeImagesByid($(this).attr("id"));
    });
	for(j = 0,len=xzImageResourceList.length; j < len; j++) {
		var oid=xzImageResourceList[j].oid;
		removeImagesByid(oid);
	}
//	baiduWeiXinMapLayer
//	var layer = getLayerById('sys_baselayer');
//	if(layer) global.map.removeLayer(layer);
//	    baiduMapLayer = new ol.layer.Tile({
//	    source: new ol.source.BaiduMap({"mapType":"sat"}),
//        projection: 'EPSG:3857'
//    })
//     baiduMapLayer.set('name', 'sys_baselayer');
//     baiduMapLayer.set('id', 'sys_baselayer');
//     baiduMapLayer.setZIndex(0);
//     global.map.addLayer(baiduMapLayer);
	 baiduMapLayer.setVisible(false); //显示卫星
     baiduWeiXinMapLayer.setVisible(true); //关闭行政
     getAllMapImages();
}

/**
* 通过id获取指定图层
**/
function getLayerById(id){
	global.map.getLayers().forEach(function(layer) {
		if (layer && layer.get('id')){
//			console.log(layer.get('id'));
//			console.log(layer.get('id') == id);
			if(layer.get('id') == id) {
				return layer;
			}
		}
	});
	return null;
}

/**
* 通过id删除指定图层
**/
function removeLayerById(id){
	global.map.getLayers().forEach(function(layer) {
		if (layer && layer.get('id')){
			if(layer.get('id') == id) {
				global.map.removeLayer(layer);
			}
		}
	});
}